//
//  ViewController.m
//  PhotoGPSdemo
//
//  Created by Alex on 12-12-20.
//  Copyright (c) 2012年 Alex. All rights reserved.
//

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface ViewController ()

@end

@implementation ViewController
@synthesize imgViews=_imgViews;
@synthesize locationManager=_locationManager;
@synthesize mediaInfo=_mediaInfo;
@synthesize image=_image;
@synthesize labs=_labs;

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
}





#pragma mark custom

-(IBAction)takePhotos:(id)sender{
    
    [self CreartLocation];
    [self openPhoto];

}

-(void)openPhoto{
    //生成图片选择控制器
    UIImagePickerController * picker = [[UIImagePickerController alloc]init];
    //设置代理
    picker.delegate = self;
    //是否允许编辑照片
    picker.allowsEditing = YES;
    
    NSString *mediaType = AVMediaTypeVideo;//读取媒体类型
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];//读取设备授权状态
    if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
        NSString *errorStr = @"应用相机权限受限,请在设置中启用";
        NSLog(@"%@", errorStr);
        
    }else{
        
        picker.sourceType=UIImagePickerControllerSourceTypeCamera;
        
        [self presentViewController:picker animated:YES completion:nil];
    }
    
}


- (IBAction)showAlbums{
    UIImagePickerController *albumPicker = [[UIImagePickerController alloc] init];
    albumPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    albumPicker.delegate = self;
    //albumPicker.allowsEditing = NO;
//    [self presentModalViewController:albumPicker animated:YES];
    [self presentViewController:albumPicker animated:YES completion:nil];
}

/*
 保存图片到相册
 */
- (void)writeCGImage:(UIImage*)image metadata:(NSDictionary *)metadata{
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    ALAssetsLibraryWriteImageCompletionBlock imageWriteCompletionBlock =
    ^(NSURL *newURL, NSError *error) {
        if (error) {
            NSLog( @"Error writing image with metadata to Photo Library: %@", error );
        } else {
            NSLog( @"Wrote image with metadata to Photo Library");
        }
    };
    
    //保存相片到相册 注意:必须使用[image CGImage]不能使用强制转换: (__bridge CGImageRef)image,否则保存照片将会报错
    [library writeImageToSavedPhotosAlbum:[image CGImage]
                                 metadata:metadata
                          completionBlock:imageWriteCompletionBlock];
}

/**
 定位功能
 */
-(void)CreartLocation{
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc]init];
        
        if ([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            
            //            // 前台定位授权 官方文档中说明info.plist中必须有NSLocationWhenInUseUsageDescription键
            //            [_mgr requestWhenInUseAuthorization];
            // 前后台定位授权 官方文档中说明info.plist中必须有NSLocationAlwaysUsageDescription键
            [_locationManager requestAlwaysAuthorization];
        }
        [_locationManager setDelegate:self];
        [_locationManager setDistanceFilter:kCLDistanceFilterNone];
        [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
        _locationManager.distanceFilter=100;
        
        //            [_locationManager requestAlwaysAuthorization];//一直定位
        
        
    }
    [_locationManager startUpdatingLocation];


}

#pragma mark UIImagePickerControlleDelegates
- (void) imagePickerController: (UIImagePickerController *) picker didFinishPickingMediaWithInfo: (NSDictionary *) info {
    NSLog(@"图片info:%@",info);
    if(picker.sourceType == UIImagePickerControllerSourceTypeCamera)
    {
        //图片
        UIImage *image= [info objectForKey:UIImagePickerControllerOriginalImage];
        self.image=image;
        self.imgViews.image=image;
//        NSLog(@"图片info:%@",info);
        //照片mediaInfo
        self.mediaInfo=[NSMutableDictionary dictionaryWithDictionary:info];
        
        
    } else if(picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary){
        __block UIImage *image= [info objectForKey:UIImagePickerControllerOriginalImage];
        self.imgViews.image=image;
        self.image=image;
        
//        NSLog(@"info:%@",info);
        __block NSMutableDictionary *imageMetadata = nil;
        NSURL *assetURL = [info objectForKey:UIImagePickerControllerReferenceURL];
        ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
        [library assetForURL:assetURL
                 resultBlock:^(ALAsset *asset)  {
                     imageMetadata = [[NSMutableDictionary alloc] initWithDictionary:asset.defaultRepresentation.metadata];
                     //控制台输出查看照片的metadata
                     NSLog(@"imageMetadata=%@",imageMetadata);
                     
                     //GPS数据
                     NSDictionary *GPSDict=[imageMetadata objectForKey:(NSString*)kCGImagePropertyGPSDictionary];
                     if (GPSDict!=nil) {
                         CLLocation *loc=[GPSDict locationFromGPSDictionary];
                         
                         self.labs.text=[NSString stringWithFormat:@"latitude:%f,  longitude:%f",loc.coordinate.latitude,loc.coordinate.longitude];
                     }
                     else{
                         self.labs.text=@"此照片没有GPS信息";
                     }
                     
                     //EXIF数据
                     NSMutableDictionary *EXIFDictionary =[[imageMetadata objectForKey:(NSString *)kCGImagePropertyExifDictionary]mutableCopy];
                     NSString * dateTimeOriginal=[[EXIFDictionary objectForKey:(NSString*)kCGImagePropertyExifDateTimeOriginal] mutableCopy];
                     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                     [dateFormatter setDateFormat:@"yyyy:MM:dd HH:mm:ss"];//yyyy-MM-dd HH:mm:ss
                     NSDate *date = [dateFormatter dateFromString:dateTimeOriginal];                     
                 }
                failureBlock:^(NSError *error) {
                }];
    }

   [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
	[picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark CLLocationManagerDelegate
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(nonnull NSArray<CLLocation *> *)locations{
    NSLog(@"定位成功！");
    [manager stopUpdatingLocation];
    
    CLLocation *newLocation = [locations lastObject];
    self.labs.text=[NSString stringWithFormat:@"latitude:%f,   longitude:%f",newLocation.coordinate.latitude,newLocation.coordinate.longitude];
    
    //获取照片元数据
    NSDictionary *dict = [_mediaInfo objectForKey:UIImagePickerControllerMediaMetadata];
    NSMutableDictionary *metadata = [NSMutableDictionary dictionaryWithDictionary:dict];
    
    //将GPS数据写入图片并保存到相册
    NSDictionary * gpsDict=[newLocation GPSDictionary];//CLLocation对象转换为NSDictionary
    if (metadata&& gpsDict) {
        [metadata setValue:gpsDict forKey:(NSString*)kCGImagePropertyGPSDictionary];
    }
    [self writeCGImage:_image metadata:metadata];

}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    NSLog(@"定位失败！");
}

// 代理方法中监听授权的改变,被拒绝有两种情况,一是真正被拒绝,二是服务关闭了
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
        {
            NSLog(@"用户未决定");
            break;
        }
            // 系统预留字段,暂时还没用到
        case kCLAuthorizationStatusRestricted:
        {
            NSLog(@"受限制");
            break;
        }
        case kCLAuthorizationStatusDenied:
        {
            // 被拒绝有两种情况 1.设备不支持定位服务 2.定位服务被关闭
            if ([CLLocationManager locationServicesEnabled]) {
                NSLog(@"真正被拒绝");
                // 跳转到设置界面
                NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                if ([[UIApplication sharedApplication] canOpenURL:url]) {
                    
                    [[UIApplication sharedApplication] openURL:url];
                }
            }
            else {
                NSLog(@"没有开启此功能");
            }
            break;
        }
        case kCLAuthorizationStatusAuthorizedAlways:
        {
            NSLog(@"前后台定位授权");
            break;
        }
        case kCLAuthorizationStatusAuthorizedWhenInUse:
        {
            NSLog(@"前台定位授权");
            break;
        }
            
        default:
            break;
    }
}

@end
